package com.jcfk.eam.service.main;

import com.jcfk.common.core.exception.CustomException;
import com.jcfk.eam.domain.dto.main.EamRepayRecordDTO;
import com.jcfk.eam.domain.dto.main.AssetChangeInfoDTO;
import com.jcfk.eam.domain.po.main.EamGrantRecord;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.query.main.EamGrantRecordQuery;
import com.jcfk.eam.domain.dto.main.EamGrantRecordDTO;
import com.jcfk.eam.domain.dto.main.EamGrantRecordDetailDTO;
import com.jcfk.eam.domain.po.main.EamGrantRecordDetail;
import com.jcfk.eam.dao.main.EamGrantRecordDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.eam.domain.query.main.EamRepayRecordQuery;
import com.jcfk.eam.enums.AssetStatus;
import com.jcfk.system.api.utils.CodeBuildUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;
import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.List;

import java.util.Date;

/**
 * 发放记录
 *
 * @author yql
 * @email 522891237@gqq.com
 * @date 2024-07-29
 */
@Service
public class EamGrantRecordService extends BaseService<EamGrantRecordDao,EamGrantRecord> {


    @Autowired
    private EamGrantRecordDetailService eamGrantRecordDetailService;

    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    /**
     * EamGrantRecord分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamGrantRecordDTO> queryByPage(DataPage<EamGrantRecordDTO> page, EamGrantRecordQuery query) {
        // 分页查询
        query.setRecordCode(StringUtils.isEmpty(query.getRecordCode()) ? query.getRecordCode() : query.getRecordCode() + "%");
        query.setOriginalVoucherNo(StringUtils.isEmpty(query.getOriginalVoucherNo()) ? query.getOriginalVoucherNo() : query.getOriginalVoucherNo() + "%");
        query.setGrantPersonName(StringUtils.isEmpty(query.getGrantPersonName()) ? query.getGrantPersonName() : query.getGrantPersonName() + "%");
        query.setReceiveDepartmentName(StringUtils.isEmpty(query.getReceiveDepartmentName()) ? query.getReceiveDepartmentName() : query.getReceiveDepartmentName() + "%");
        query.setReceivePersonName(StringUtils.isEmpty(query.getReceivePersonName()) ? query.getReceivePersonName() : query.getReceivePersonName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    public DataPage<EamRepayRecordDTO> queryRepayByPage(DataPage<EamRepayRecordDTO> page, EamRepayRecordQuery query) {
        // 分页查询
        query.setRecordCode(StringUtils.isEmpty(query.getRecordCode()) ? query.getRecordCode() : query.getRecordCode() + "%");
        query.setOriginalVoucherNo(StringUtils.isEmpty(query.getOriginalVoucherNo()) ? query.getOriginalVoucherNo() : query.getOriginalVoucherNo() + "%");
        query.setGrantPersonName(StringUtils.isEmpty(query.getGrantPersonName()) ? query.getGrantPersonName() : query.getGrantPersonName() + "%");
        query.setReceiveDepartmentName(StringUtils.isEmpty(query.getReceiveDepartmentName()) ? query.getReceiveDepartmentName() : query.getReceiveDepartmentName() + "%");
        query.setReceivePersonName(StringUtils.isEmpty(query.getReceivePersonName()) ? query.getReceivePersonName() : query.getReceivePersonName() + "%");
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : query.getAssetName() + "%");
        query.setUsingDepartmentName(StringUtils.isEmpty(query.getUsingDepartmentName()) ? query.getUsingDepartmentName() : query.getUsingDepartmentName() + "%");
        query.setUsingPersonName(StringUtils.isEmpty(query.getUsingPersonName()) ? query.getUsingPersonName() : query.getUsingPersonName() + "%");
        query.setLocationBeforeGrant(StringUtils.isEmpty(query.getLocationBeforeGrant()) ? query.getLocationBeforeGrant() : query.getLocationBeforeGrant() + "%");
        query.setLocationAfterGrant(StringUtils.isEmpty(query.getLocationAfterGrant()) ? query.getLocationAfterGrant() : query.getLocationAfterGrant() + "%");
        query.setRepayPersonName(StringUtils.isEmpty(query.getRepayPersonName()) ? query.getRepayPersonName() : query.getRepayPersonName() + "%");
        query.setLocationAfterRepay(StringUtils.isEmpty(query.getLocationAfterRepay()) ? query.getLocationAfterRepay() : query.getLocationAfterRepay() + "%");

        page = this.baseMapper.queryRepayByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamGrantRecordDTO>
     */
    public List<EamGrantRecordDTO> getList(EamGrantRecordQuery query) {
        // 查询条件
        QueryWrapper<EamGrantRecord> qw = new QueryWrapper<>();
        qw.lambda().like(!StrUtil.isEmpty(query.getRecordCode()), EamGrantRecord::getRecordCode, query.getRecordCode());
        qw.lambda().like(!StrUtil.isEmpty(query.getOriginalVoucherNo()), EamGrantRecord::getOriginalVoucherNo, query.getOriginalVoucherNo());
        qw.lambda().eq(query.getAssetKind() != null, EamGrantRecord::getAssetKind, query.getAssetKind());
        qw.lambda().ge(!StrUtil.isEmpty(query.getGrantDateStart()), EamGrantRecord::getGrantDate, query.getGrantDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getGrantDateEnd()), EamGrantRecord::getGrantDate, query.getGrantDateEnd());
        qw.lambda().eq(!StrUtil.isEmpty(query.getGrantPersonId()), EamGrantRecord::getGrantPersonId, query.getGrantPersonId());
        qw.lambda().like(!StrUtil.isEmpty(query.getGrantPersonName()), EamGrantRecord::getGrantPersonName, query.getGrantPersonName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getReceiveDepartmentId()), EamGrantRecord::getReceiveDepartmentId, query.getReceiveDepartmentId());
        qw.lambda().like(!StrUtil.isEmpty(query.getReceiveDepartmentName()), EamGrantRecord::getReceiveDepartmentName, query.getReceiveDepartmentName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getReceivePersonId()), EamGrantRecord::getReceivePersonId, query.getReceivePersonId());
        qw.lambda().like(!StrUtil.isEmpty(query.getReceivePersonName()), EamGrantRecord::getReceivePersonName, query.getReceivePersonName());
        qw.lambda().eq(query.getIsAudit() != null, EamGrantRecord::getIsAudit, query.getIsAudit());
        qw.lambda().eq(query.getDeleted() != null, EamGrantRecord::getDeleted, query.getDeleted());
        qw.lambda().eq(!StrUtil.isEmpty(query.getOrganizationId()), EamGrantRecord::getOrganizationId, query.getOrganizationId());
        qw.lambda().ge(!StrUtil.isEmpty(query.getCreateTimeStart()), EamGrantRecord::getCreateTime, query.getCreateTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getCreateTimeEnd()), EamGrantRecord::getCreateTime, query.getCreateTimeEnd());
        qw.lambda().ge(!StrUtil.isEmpty(query.getLastUpdateTimeStart()), EamGrantRecord::getLastUpdateTime, query.getLastUpdateTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getLastUpdateTimeEnd()), EamGrantRecord::getLastUpdateTime, query.getLastUpdateTimeEnd());
        // 查询数据
        List<EamGrantRecord> list = super.list(qw);

        return convertList(list, EamGrantRecordDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamGrantRecordDTO>
     */
    public List<EamGrantRecordDetailDTO> getDetails(EamGrantRecordQuery query) {
        // 查询条件
        QueryWrapper<EamGrantRecordDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EamGrantRecordDetail::getRecordId, query.getId());

        // 查询数据
        List<EamGrantRecordDetail> list = eamGrantRecordDetailService.list(qw);

        return convertList(list, EamGrantRecordDetailDTO.class);
    }


    /**
     * 判断EamGrantRecord是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamGrantRecordDTO dto) {
        QueryWrapper<EamGrantRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        return RetResult.ok();
    }

    /**
     * 插入发放记录
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamGrantRecordDTO dto) {

        // 保存
        EamGrantRecord item = new EamGrantRecord();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        item.setIsAudit(0);
        item.setRecordCode(CodeBuildUtils.buildCode("record", "record"));

        super.save(item);

        int i = 1;
        // 设置关联主键
        for (EamGrantRecordDetailDTO detail : dto.getDetails()) {
            detail.setRecordId(item.getId());
            detail.setSeq(String.valueOf(i));
            detail.setIsRepay(0);
            i ++ ;
        }

        // 保存明细表
        eamGrantRecordDetailService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 更新发放记录
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamGrantRecordDTO dto) {
        // 保存
        EamGrantRecord item = new EamGrantRecord();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        int i = 1;
        // 设置关联主键
        for (EamGrantRecordDetailDTO detail : dto.getDetails()) {
            detail.setRecordId(item.getId());
            detail.setSeq(String.valueOf(i));
            i ++ ;
        }
        // 保存明细表
        eamGrantRecordDetailService.saveBatch(dto.getDetails(), item.getId());
    }

    /**
     * 根据批量主键删除发放记录(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamGrantRecordDTO dto) {

        EamGrantRecord item = new EamGrantRecord();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamGrantRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 根据批量主键删除发放记录(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicExamineList(EamGrantRecordDTO dto) {

        EamGrantRecord item = new EamGrantRecord();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setIsAudit(1);

        QueryWrapper<EamGrantRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        //校验资产台账数据是否合法
        // 查询条件
        QueryWrapper<EamGrantRecordDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(EamGrantRecordDetail :: getDeleted, 0);
        qw.lambda().in(EamGrantRecordDetail::getRecordId,  dto.getIds());
        List<EamGrantRecordDetail> list = eamGrantRecordDetailService.list(qw);
        if(list != null && !list.isEmpty()){
            EamAssetInfo eamAssetInfo;
            for (EamGrantRecordDetail set : list){
                eamAssetInfo = eamAssetInfoService.getById(set.getAssetId());
                if(eamAssetInfo == null || AssetStatus.STOCK.getValue() != eamAssetInfo.getAssetStatus() || eamAssetInfo.getDeleted() == 1){
                    throw new CustomException("资产台账数据不合法，审核失败");
                }
                //更新资产台账数据
                AssetChangeInfoDTO assetChangeInfo=new AssetChangeInfoDTO();
                assetChangeInfo.setUsingDepartmentId(set.getUsingDepartmentId());
                assetChangeInfo.setUsingDepartmentName(set.getUsingDepartmentName());
                assetChangeInfo.setUsingPersonId(set.getUsingPersonId());
                assetChangeInfo.setUsingPersonName(set.getUsingPersonName());
                assetChangeInfo.setLocationId(set.getLocationAfterGrantId());
                assetChangeInfo.setLocationName(set.getLocationAfterGrant());
                assetChangeInfo.setAssetStatus(AssetStatus.EXERCISE.getValue());
                eamAssetInfoService.changeInfo(eamAssetInfo,assetChangeInfo);
            }
        }

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamGrantRecord item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取发放记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamGrantRecordDTO get(String id) {
        // 查询数据
        EamGrantRecord item = this.baseMapper.selectById(id);
        EamGrantRecordDTO dto = new EamGrantRecordDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 根据主键获取归还记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamRepayRecordDTO getDetails(String id) {
        // 查询数据
        EamRepayRecordDTO item = this.baseMapper.getDetails(id);
        return item;
    }

    /**
     * 根据主键获取发放记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteitem(String id) {
        EamGrantRecord item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

